package com.lkd.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lkd.dto.PartnerDto;
import com.lkd.entity.Partner;
import com.lkd.mapper.PartnerMapper;
import com.lkd.mapper.VendingMachineMapper;
import com.lkd.result.PageBean;
import com.lkd.service.PartnerService;
import com.lkd.vo.PartnerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class PartnerServiceImpl implements PartnerService {

    @Autowired
    private PartnerMapper mapper;

    @Autowired
    private VendingMachineMapper vendingMachineMapper;

    @Override
    public Partner getById(Long id) {
        return mapper.getById(id);
    }

    @Override
    public boolean create(Partner partner) {
        partner.setPassword("123");
        partner.setCreateTime(LocalDateTime.now());
        partner.setUpdateTime(LocalDateTime.now());
        return mapper.create(partner);
    }

    @Override
    public boolean update(Partner partner) {
        partner.setUpdateTime(LocalDateTime.now());
        return mapper.update(partner);
    }

    @Override
    public boolean delete(Long id) {
        return mapper.delete(id);
    }

    @Override
    public List<Partner> getAll() {
        return mapper.getAll();
    }

    @Override
    public PageBean<PartnerVo> findByPage(PartnerDto dto) {
        PageHelper.startPage(dto.getPageIndex(),dto.getPageSize());

        List<PartnerVo> list = mapper.findList(dto);
        Page<PartnerVo> page = (Page<PartnerVo>) list;

        //遍历集合,获取list
        if (CollectionUtil.isNotEmpty(list)){
            for (PartnerVo partnerVo : list) {
                Integer count = vendingMachineMapper.countByOwnerId(partnerVo.getId());
                partnerVo.setVmCount(count);
            }
        }

        //返回结果
        PageBean<PartnerVo> pageBean = new PageBean<>();
        pageBean.setPageIndex(page.getPageNum());
        pageBean.setPageSize(page.getPageSize());
        pageBean.setTotalPage((long)page.getPages());
        pageBean.setTotalCount(page.getTotal());
        pageBean.setCurrentPageRecords(page.getResult());
        return pageBean;
    }
}
